<?php
// +----------------------------------------------------------------------
// | 小说系统 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;
use app\common\model\UploadPath;
use app\common\model\UserHonour;
class Index extends Admin {

	public function index() {
	    //exit();
		$data['is_administrator'] = is_administrator();
		$data['new'] = db('notice')->where('status=1')->order('id DESC')->limit(1)->find();
		$map['status'] = 1;
		$type = input('type');
		if(!empty($type)){
			$map['type'] = input('type');
		}
		
		$list = db('notice')->where($map)->order('id desc')->paginate(config('list_rows'));
		$data['list'] = $list;
		$data['type'] = input('type');
		$data['page'] = $list->render();

        // 消息列表
        $message = db('message')->order('create_time', 'desc')->select();
		$time='';
		if(isset($message[0])){
			$time=date('Ymd',$message[0]['create_time']);
		}
		$messagelist=[];
        foreach ($message as $key => $v) {
            $message[$key]['sender'] = db('member')->where('uid', $v['sender'])->value('username');
            $message[$key]['send_date'] = date('Y.m.d H:i:s', $v['create_time']);
			$vl=date('Ymd' ,$v['create_time']);
			if($time!=''&&$time==$vl){
				$messagelist[]=$message[$key];
			}
        }

        // 部门列表
        $groupList = db('auth_group')->where('pid',0)->column('description', 'id');
		$uid=session('user_auth.uid');
		$userModel=model('User');
		//个人信息
		$userInfo=$userModel->where('uid',$uid)->find();
		$uplodmodel=new UploadPath();
		$handbook=$uplodmodel->where(['type'=>0,'status'=>1])->order('id desc')->find();
		// $handbookImage=$this->UploadImage($handbook);

		$this->assign(compact('data', 'message', 'groupList','userInfo','handbook','messagelist'));
		$this->setMeta('后台首页');
		return $this->fetch();
	}
	public function api_get_notice() {
		$data = array(
			"id"=>"3",
			"title"=>"本周热门推荐榜单",
			"content"=>"一、新品漫画：\n《暧昧公寓》-----数据不错，可上量尝试！\n\n二、热门轻小说推荐：\n1、《留住有情人》\n2、《那天我们爱了》\n3、《非你不嫁》",
			"created_at"=>"1511493100",
			"created_by_id"=>"635",
			"target_user_type"=>"all"
		);
		header('Content-type: text/json'); 		
		echo json_encode($data);
		exit();	
	}

	public function login($username = '', $password = '', $verify = '') {
		if (IS_POST) {
			if (!$username || !$password) {
				return $this->error('用户名或者密码不能为空！', 'admin/order/index');
			}

			//验证码验证
			//$this->checkVerify($verify);

			$user = model('User');
			$uid  = $user->login($username, $password);
			if ($uid > 0) {
				//记录行为
				action_log('login', 'Member', $uid, session('user_auth.uid'));
              //  $this->redirect('admin/order/index');
			    return $this->success('登录成功！', '/');
               // return $this->fetch('order/index');
			} else {
				switch ($uid) {
				case -1:$error = '用户不存在或被禁用！';
					break; //系统级别禁用
				case -2:$error = '密码错误！';
					break;
				default:$error = '未知错误！';
					break; // 0-接口参数错误（调试阶段使用）
				}
				return $this->error($error, '');
			}
		} else {
			return $this->fetch();
		}
	}
	/**
	 * 注册页面
	 */
	public function register(){
		if (IS_POST) {
			$model = model('User');
			$honourmodel=new UserHonour();
			$data = $this->request->param();
			//创建注册用户
			$result = $model->register($data['username'], $data['password'], $data['repassword'], $data['email'], false);
			if ($result) {
				$data['uid']=$result;
				if(array_key_exists("mobile", $data)){
					if($data['mobile']==''||$data['mobile']=='0'){
						unset($data['mobile']);
					}
				}
				if(array_key_exists("birthday", $data)){
					if($data['birthday']==''){
						unset($data['birthday']);
					}
				}
				if(array_key_exists("birthday", $data)){
					if($data['birthday']==''){
						unset($data['birthday']);
					}
				}
				if(array_key_exists("honour", $data)){
					if($data['birthday']!=''){
						$honourmodel->edit($data['honour'],$data['uid']);
					}
					unset($data['honour']);
				}
				$data['status']=0;
				$reuslt = $model->editUser($data, true);
				return $this->success('添加成功！', url('admin/index/login'));
			} else {
				return $this->error($model->getError());
			}
		} else {
			$members =  db('member')->column('nickname', 'uid');
            $situation = db('auth_group')->where('pid', '>', 0)->column('title', 'id');
			$grouplist = db('auth_group')->where('pid',  0)->column('title', 'id');
			$data = array(
				'grouplist' =>$grouplist,
				'situation' =>$situation,
				'members'=>$members
			);
			$this->assign($data);
			return $this->fetch();
		}
	}
	public function logout() {
		$user = model('User');
		action_log('logout', 'Member', session('user_auth.uid'), session('user_auth.uid'));
		$user->logout();
		$this->redirect('admin/index/login');
	}

	public function clear() {
		if (IS_POST) {
			$clear = input('post.clear/a', array());

			foreach ($clear as $key => $value) {
				if ($value == 'cache') {
					\think\Cache::clear(); // 清空缓存数据
				} elseif ($value == 'log') {
					\think\Log::clear();
				}
			}
			//opcache_reset();//清空opcache缓存

			return $this->success("更新成功！", url('admin/index/index'));
		} else {
			$keylist = array(
				array('name' => 'clear', 'title' => '更新缓存', 'type' => 'checkbox', 'help' => '', 'option' => array(
					'cache' => '缓存数据',
					'log'   => '日志数据',
				),
				),
			);
			$data = array(
				'keyList' => $keylist,
			);
			$this->assign($data);
			$this->setMeta("更新缓存");
			return $this->fetch('public/edit');
		}
	}

	public function sys_tz() {		
		//服务器标识
		$php_uname = @php_uname();
		//服务器操作系统
		$os = explode(" ", php_uname());
		$oss = $os[0];
		//内核版本
		if('/'==DIRECTORY_SEPARATOR){
			$Kernelversion = $os[2];
		}else{
			$Kernelversion = $os[1];
		}

		$sysInfo = $this->sys_linux();
	}

	//linux系统探测
	public function sys_linux()
	{
		// CPU
		if (false === ($str = @file("/proc/cpuinfo"))) return false;
		$str = implode("", $str);
		@preg_match_all("/model\s+name\s{0,}\:+\s{0,}([\w\s\)\(\@.-]+)([\r\n]+)/s", $str, $model);
		
		@preg_match_all("/cpu\s+MHz\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/", $str, $mhz);
		@preg_match_all("/cache\s+size\s{0,}\:+\s{0,}([\d\.]+\s{0,}[A-Z]+[\r\n]+)/", $str, $cache);
		@preg_match_all("/bogomips\s{0,}\:+\s{0,}([\d\.]+)[\r\n]+/", $str, $bogomips);
		var_dump($model[1]);
		exit();
		if (false !== is_array($model[1]))
		{
			$res['cpu']['num'] = sizeof($model[1]);
			/*
			for($i = 0; $i < $res['cpu']['num']; $i++)
			{
				$res['cpu']['model'][] = $model[1][$i].'&nbsp;('.$mhz[1][$i].')';
				$res['cpu']['mhz'][] = $mhz[1][$i];
				$res['cpu']['cache'][] = $cache[1][$i];
				$res['cpu']['bogomips'][] = $bogomips[1][$i];
			}*/
			if($res['cpu']['num']==1)
				$x1 = '';
			else
				$x1 = ' ×'.$res['cpu']['num'];
			$mhz[1][0] = ' | 频率:'.$mhz[1][0];
			$cache[1][0] = ' | 二级缓存:'.$cache[1][0];
			$bogomips[1][0] = ' | Bogomips:'.$bogomips[1][0];
			$res['cpu']['model'][] = $model[1][0].$mhz[1][0].$cache[1][0].$bogomips[1][0].$x1;
			if (false !== is_array($res['cpu']['model'])) $res['cpu']['model'] = implode("<br />", $res['cpu']['model']);
			var_dump($res);
			exit();
			if (false !== is_array($res['cpu']['mhz'])) $res['cpu']['mhz'] = implode("<br />", $res['cpu']['mhz']);
			if (false !== is_array($res['cpu']['cache'])) $res['cpu']['cache'] = implode("<br />", $res['cpu']['cache']);
			if (false !== is_array($res['cpu']['bogomips'])) $res['cpu']['bogomips'] = implode("<br />", $res['cpu']['bogomips']);
		}

		// NETWORK

		// UPTIME
		if (false === ($str = @file("/proc/uptime"))) return false;
		$str = explode(" ", implode("", $str));
		$str = trim($str[0]);
		$min = $str / 60;
		$hours = $min / 60;
		$days = floor($hours / 24);
		$hours = floor($hours - ($days * 24));
		$min = floor($min - ($days * 60 * 24) - ($hours * 60));
		if ($days !== 0) $res['uptime'] = $days."天";
		if ($hours !== 0) $res['uptime'] .= $hours."小时";
		$res['uptime'] .= $min."分钟";

		// MEMORY
		if (false === ($str = @file("/proc/meminfo"))) return false;
		$str = implode("", $str);
		preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buf);
		preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buffers);

		$res['memTotal'] = round($buf[1][0]/1024, 2);
		$res['memFree'] = round($buf[2][0]/1024, 2);
		$res['memBuffers'] = round($buffers[1][0]/1024, 2);
		$res['memCached'] = round($buf[3][0]/1024, 2);
		$res['memUsed'] = $res['memTotal']-$res['memFree'];
		$res['memPercent'] = (floatval($res['memTotal'])!=0)?round($res['memUsed']/$res['memTotal']*100,2):0;

		$res['memRealUsed'] = $res['memTotal'] - $res['memFree'] - $res['memCached'] - $res['memBuffers']; //真实内存使用
		$res['memRealFree'] = $res['memTotal'] - $res['memRealUsed']; //真实空闲
		$res['memRealPercent'] = (floatval($res['memTotal'])!=0)?round($res['memRealUsed']/$res['memTotal']*100,2):0; //真实内存使用率

		$res['memCachedPercent'] = (floatval($res['memCached'])!=0)?round($res['memCached']/$res['memTotal']*100,2):0; //Cached内存使用率

		$res['swapTotal'] = round($buf[4][0]/1024, 2);
		$res['swapFree'] = round($buf[5][0]/1024, 2);
		$res['swapUsed'] = round($res['swapTotal']-$res['swapFree'], 2);
		$res['swapPercent'] = (floatval($res['swapTotal'])!=0)?round($res['swapUsed']/$res['swapTotal']*100,2):0;

		// LOAD AVG
		if (false === ($str = @file("/proc/loadavg"))) return false;
		$str = explode(" ", implode("", $str));
		$str = array_chunk($str, 4);
		$res['loadAvg'] = implode(" ", $str[0]);

		return $res;
	}

	

	/******切换公众号*****/
	public function switch() {
		$wxmpid = input('wxmpid');
		if($wxmpid == 100000){
		    session('wxmpid', 100000);
            session('webname','全部');
            echo json_encode(array("code"=>200));
            exit();
		}
		$wxmp = db('wxmp')->where('id ='.$wxmpid." and status =1")->field('id,webname')->find();
		if($wxmp){
			/* 更新SESSION */
			session('wxmpid', $wxmp['id']);
			session('webname',$wxmp['webname']);
			echo json_encode(array("code"=>200));
		}else{
			echo json_encode(array("code"=>0));
		}
		exit();
	}

	public function menupage() {
		$wxmpid =session('wxmpid');
		$uid =session('user_auth.uid');
		$domain = get_agent_domain($uid,0,$wxmpid);
		$list = config('menupage');

		$data = [
			"list"=>$list,
			"domain"=>$domain
		];
		$this->assign($data);
		$this->setMeta('页面推广');
		return $this->fetch();
	}

    /**
     * Notes: 添加消息
     * @author: Zhu
     * @since: 2022/11/29 16:14
     */
	public function addMessage()
    {
        if(IS_POST){
            $post = input('post.');
            $post['sender'] = session('user_auth.uid');
            $post['create_time'] = time();
            $messigeId = db('message')->insertGetId($post);
            if ($post['recipient'] != 999) {
                $recipient = db('member')->where('group', $post['recipient'])->column('uid');
            } else {
                $recipient = db('member')->column('uid');
            }
            $data = [];
            foreach ($recipient as $k => $v) {
                $data[] = [
                    'uid' => $v,
                    'message_id' => $messigeId,
                    'is_read' => 1,
                    'create_time' => time()
                ];
            }

           db('message_detail')->insertAll($data);
            return $this->success("成功！");
        }
        return $this->error("失败！");
    }
	/**
	 * 保存首页上传文件
	 */
	public function IndexUpload(){
		$post = input('post.');
		$post['uid'] = session('user_auth.uid');
		if(is_null($post['path_file'])){
			return $this->error("上传路径不能为空");
		}
		if(!isset($post['title'])){
			$post['title']='';
		}
		if(is_null($post['type'])){
			return $this->error("类型不能空");
		}
		$post['create_time']=time();
		$post['status']='1';
		$uplodmodel=new UploadPath();
		$uplodmodel->where(['uid'=>$post['uid'],'type'=>$post['type']])->update(['update_time'=>time(),'status'=>'2']);
		$list=$uplodmodel->insert($post);
		if($list){
			return $this->success('添加成功');
		}else{
			return $this->error("添加失败");
		}
	}
}